package com.ssy.lingxi.transaction.serviceimpl;

import cn.hutool.core.bean.BeanUtil;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.message.api.constant.MessageTemplateCode;
import com.ssy.lingxi.message.api.feign.SystemMessageControllerFeign;
import com.ssy.lingxi.message.api.vo.request.SystemMessageRequest;
import com.ssy.lingxi.report.api.enums.ConfirmInquiryQuotationOperateTypeEnum;
import com.ssy.lingxi.report.api.enums.OperateDataSourceEnum;
import com.ssy.lingxi.report.api.feign.ReportControllerFeign;
import com.ssy.lingxi.report.api.vo.request.OperateNoticeVO;
import com.ssy.lingxi.transaction.api.common.OrderConstant;
import com.ssy.lingxi.transaction.api.dto.request.*;
import com.ssy.lingxi.transaction.api.dto.response.*;
import com.ssy.lingxi.transaction.api.enums.*;
import com.ssy.lingxi.transaction.entity.Inquiry;
import com.ssy.lingxi.transaction.entity.InquiryProduct;
import com.ssy.lingxi.transaction.entity.Quote;
import com.ssy.lingxi.transaction.entity.record.ConfirmQuoteInteriorRecord;
import com.ssy.lingxi.transaction.entity.record.InquiryExternalRecord;
import com.ssy.lingxi.transaction.entity.record.InquiryInteriorRecord;
import com.ssy.lingxi.transaction.repository.*;
import com.ssy.lingxi.transaction.service.IConfirmQuoteService;
import com.ssy.lingxi.workflow.api.feign.ProcessFeign;
import com.ssy.lingxi.workflow.api.model.contant.ProcessEnum;
import com.ssy.lingxi.workflow.api.model.vo.request.ExternalProcessQueryVO;
import com.ssy.lingxi.workflow.api.model.vo.request.InternalProcessQueryVO;
import com.ssy.lingxi.workflow.api.model.vo.request.TaskExecuteVO;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleProcessDefVO;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleTaskCompleteVO;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleTaskVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 交易中心-确认询价报价
 *
 * @author wrc
 * @date 2020/8/19
 */
@Slf4j
@Service
public class ConfirmQuoteServiceImpl implements IConfirmQuoteService {

    @Resource
    InquiryRepository inquiryRepository;
    
    @Resource
    InquiryProductRepository inquiryProductRepository;
    
    @Resource
    QuoteRepository quoteRepository;
    
    @Resource
    ConfirmQuoteInteriorRecordRepository confirmQuoteInteriorRecordRepository;

    @Resource
    InquiryExternalRecordRepository inquiryExternalRecordRepository;
    
    @Resource
    InquiryInteriorRecordRepository inquiryInteriorRecordRepository;
    
    @Resource
    ProcessFeign processFeign;
    
    @Resource
    ReportControllerFeign reportControllerFeign;
    
    @Resource
    SystemMessageControllerFeign systemMessageControllerFeign;

    /**
     * 确认询价报价-报价单列表查询
     */
    @Override
    public Wrapper<PageData<ConfirmQuoteListResponse>> notarizeEnquiryProductQuotationList(ProductQuotationListRequest request, UserLoginCacheDTO sysUser) {
        Pageable page = PageRequest.of(request.getCurrent(), request.getPageSize());
        Page<Quote> result = quoteRepository.findAll(getSpecification(request, sysUser.getMemberId(), sysUser.getMemberRoleId(), OrderConstant.ConfirmQuoteQueryType.CONFIRM_QUOTE_ALL), page);
        List<ConfirmQuoteListResponse> countryAreaListResponseList = result.getContent().stream().map(quote -> {
            ConfirmQuoteListResponse confirmQuoteListResponse = BeanUtil.copyProperties(quote, ConfirmQuoteListResponse.class);
            confirmQuoteListResponse.setInteriorState(quote.getConfirmInteriorState());
            confirmQuoteListResponse.setInteriorStateName(ConfirmQuoteInteriorStatusEnum.getName(quote.getConfirmInteriorState()));
            confirmQuoteListResponse.setExternalStateName(InquiryExternalStatusEnum.getName(confirmQuoteListResponse.getExternalState()));
            confirmQuoteListResponse.setOfferMemberId(quote.getCreateMemberId());
            confirmQuoteListResponse.setOfferMemberName(quote.getCreateMemberName());
            confirmQuoteListResponse.setOfferMemberRoleId(quote.getCreateRoleId());
            confirmQuoteListResponse.setIsShowPurchaseOrder(InquiryExternalStatusEnum.ACCEPT_OFFER.getState().equals(confirmQuoteListResponse.getExternalState()));

            List<InquiryProduct> inquiryProductList = quote.getInquiryProductList();
            if(!CollectionUtils.isEmpty(inquiryProductList)){
                confirmQuoteListResponse.setImgUrl(inquiryProductList.get(0).getImgUrl());
            }
            return confirmQuoteListResponse;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(result.getTotalElements(), countryAreaListResponseList));
    }

    /**
     * 构建查询条件
     */
    private Specification<Quote> getSpecification(ProductQuotationListRequest request, Long memberId, Long memberRoleId, Integer queryType) {
        return (Specification<Quote>) (root, query, criteriaBuilder) -> {
            Predicate finalConditions = criteriaBuilder.conjunction();

            Long shopId = request.getShopId();
            String keyword = request.getKeyword();
            String details = request.getDetails();
            String inquiryListNo = request.getInquiryListNo();
            String quotationNo = request.getQuotationNo();
            String memberName = request.getMemberName();
            String offerMemberName = request.getOfferMemberName();
            Long startDocumentsTime = request.getStartDocumentsTime();
            Long endDocumentsTime = request.getEndDocumentsTime();
            Integer externalState = request.getExternalState();
            Integer interiorState = request.getInteriorState();

            //商城id
            if (shopId != null && shopId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("shopId"), shopId));
            }
            //关键字
            if(StringUtils.isNotEmpty(keyword)){
                Predicate predicate = criteriaBuilder.or(criteriaBuilder.like(root.get("inquiryListNo"), "%" + keyword + "%"), criteriaBuilder.like(root.get("quotationNo"), "%" + keyword + "%"));
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }
            //询价会员id
            if (memberId != null && memberId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("memberId"), memberId));
            }
            //询价会员角色id
            if (memberRoleId != null && memberRoleId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("memberRoleId"), memberRoleId));
            }
            //描述
            if(StringUtils.isNotEmpty(details)){
                Predicate predicate = criteriaBuilder.like(root.get("details"), "%" + details + "%");
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }
            //询价单号
            if(StringUtils.isNotEmpty(inquiryListNo)){
                Predicate predicate = criteriaBuilder.like(root.get("inquiryListNo"), "%" + inquiryListNo + "%");
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }
            //报价单号
            if(StringUtils.isNotEmpty(quotationNo)){
                Predicate predicate = criteriaBuilder.like(root.get("quotationNo"), "%" + quotationNo + "%");
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }
            //询价会员名称
            if(StringUtils.isNotEmpty(memberName)){
                Predicate predicate = criteriaBuilder.like(root.get("memberName"), "%" + memberName + "%");
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }
            //报价会员名称
            if(StringUtils.isNotEmpty(offerMemberName)){
                Predicate predicate = criteriaBuilder.like(root.get("createMemberName"), "%" + offerMemberName + "%");
                finalConditions = criteriaBuilder.and(finalConditions, predicate);
            }
            //开始单据时间
            if(startDocumentsTime != null && startDocumentsTime > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.ge(root.get("voucherTime"), startDocumentsTime));
            }
            //结束单据时间
            if(endDocumentsTime != null && endDocumentsTime > 0){
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.le(root.get("voucherTime"), endDocumentsTime));
            }
            //状态
            if (queryType.equals(OrderConstant.ConfirmQuoteQueryType.CONFIRM_QUOTE_ALL)) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("interiorState"), 5));
                if (externalState != null && externalState > 0) {
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("externalState"), externalState));
                }
                if (interiorState != null && interiorState > 0) {
                    finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("confirmInteriorState"), interiorState));
                }
            } else if (queryType.equals(OrderConstant.ConfirmQuoteQueryType.CONFIRM_QUOTE_NOT_SUBMIT)) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("confirmInteriorState"), 1));
            } else if (queryType.equals(OrderConstant.ConfirmQuoteQueryType.CONFIRM_QUOTE_CHECK_ONE)) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("confirmInteriorState"), 2));
            } else if (queryType.equals(OrderConstant.ConfirmQuoteQueryType.CONFIRM_QUOTE_CHECK_TWO)) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("confirmInteriorState"), 3));
            } else if (queryType.equals(OrderConstant.ConfirmQuoteQueryType.CONFIRM_QUOTE_NOT_CONFIRM)) {
                List<Integer> stateList = new ArrayList<>();
                stateList.add(4);
                stateList.add(6);
                stateList.add(7);
                stateList.add(8);
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.and(criteriaBuilder.in(root.get("confirmInteriorState")).value(stateList), criteriaBuilder.equal(root.get("externalState"), 3)));
            }
            //排序
            Order createTimeOrder = criteriaBuilder.desc(root.get("id"));

            return query.orderBy(createTimeOrder).where(finalConditions).getRestriction();
        };
    }

    /**
     * 报价单详情
     */
    @Override
    public Wrapper<ProductQuotationDetailsResponse> productQuotationDetails(ProductQuotationDetailsRequest request, UserLoginCacheDTO sysUser) {
        ProductQuotationDetailsResponse productQuotationDetailsResponse = new ProductQuotationDetailsResponse();
        Quote productQuotation = quoteRepository.findById(request.getId()).orElse(null);
        if (null == productQuotation) {
            return Wrapper.fail(ResponseCode.PURCHASE_DATA_RECORDS_DON_T_EXIST);
        }
        BeanUtils.copyProperties(productQuotation, productQuotationDetailsResponse);
        productQuotationDetailsResponse.setEnclosureUrls(productQuotation.getEnclosureUrls());
        productQuotationDetailsResponse.setSupplyMembersId(productQuotation.getCreateMemberId());
        productQuotationDetailsResponse.setSupplyMembersName(productQuotation.getCreateMemberName());
        productQuotationDetailsResponse.setSupplyMembersRoleId(productQuotation.getCreateRoleId());
        productQuotationDetailsResponse.setExternalStateName(InquiryExternalStatusEnum.getName(productQuotationDetailsResponse.getExternalState()));
        productQuotationDetailsResponse.setInteriorStateName(QuoteInteriorStatusEnum.getName(productQuotationDetailsResponse.getInteriorState()));
        //获取外部流转记录
        getExternalLog(productQuotationDetailsResponse, productQuotation.getInquiryListId(), sysUser);
        //查询内部流程
        getinteriorLog(productQuotationDetailsResponse, productQuotation.getId(), sysUser);
        List<InquiryProduct> inquiryListProducts = inquiryProductRepository.findAllByQuoteId(productQuotation.getId());
        if (!CollectionUtils.isEmpty(inquiryListProducts)) {
            List<QuotationtProductListResponse> collect = inquiryListProducts.stream().map(temp -> {
                QuotationtProductListResponse quotationtProductListResponse = new QuotationtProductListResponse();
                BeanUtils.copyProperties(temp, quotationtProductListResponse);
                quotationtProductListResponse.setMemberId(temp.getMemberId());
                quotationtProductListResponse.setMemberRoleId(temp.getMemberRoleId());
                return quotationtProductListResponse;
            }).collect(Collectors.toList());
            productQuotationDetailsResponse.setProducts(collect);
        }
        return Wrapper.success(productQuotationDetailsResponse);
    }

    /**
     * 待提交审核报价单
     * @author wrc
     * @date 2020/8/19
     */
    @Override
    public Wrapper<PageData<ConfirmQuoteListResponse>> notarizeEnquiryQuotedPriceList(ProductQuotationListRequest request, UserLoginCacheDTO sysUser) {
        Pageable page = PageRequest.of(request.getCurrent(), request.getPageSize());
        Page<Quote> result = quoteRepository.findAll(getSpecification(request, sysUser.getMemberId(), sysUser.getMemberRoleId(), OrderConstant.ConfirmQuoteQueryType.CONFIRM_QUOTE_NOT_SUBMIT), page);
        List<ConfirmQuoteListResponse> countryAreaListResponseList = result.getContent().stream().map(quote -> {
            ConfirmQuoteListResponse confirmQuoteListResponse = BeanUtil.copyProperties(quote, ConfirmQuoteListResponse.class);
            confirmQuoteListResponse.setInteriorState(quote.getConfirmInteriorState());
            confirmQuoteListResponse.setInteriorStateName(ConfirmQuoteInteriorStatusEnum.getName(quote.getConfirmInteriorState()));
            confirmQuoteListResponse.setExternalStateName(InquiryExternalStatusEnum.getName(confirmQuoteListResponse.getExternalState()));
            confirmQuoteListResponse.setOfferMemberId(quote.getCreateMemberId());
            confirmQuoteListResponse.setOfferMemberName(quote.getCreateMemberName());
            confirmQuoteListResponse.setOfferMemberRoleId(quote.getCreateRoleId());
            return confirmQuoteListResponse;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(result.getTotalElements(), countryAreaListResponseList));
    }

    /**
     * 确认询价报价-询价单详情
     * @author wrc
     * @date 2020/8/19
     */
    @Override
    public Wrapper<NotarizeEnquiryQuotedPriceDetailsResponse> notarizeEnquiryQuotedPriceDetails(NotarizeEnquiryQuotedPriceDetailsRequest request, UserLoginCacheDTO sysUser) {
        NotarizeEnquiryQuotedPriceDetailsResponse response = new NotarizeEnquiryQuotedPriceDetailsResponse();
        Inquiry inquiryList = inquiryRepository.findById(request.getId()).orElse(null);
        if (null == inquiryList) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        BeanUtils.copyProperties(inquiryList, response);
        //查询商品详情
        List<InquiryListProductResponse> inquiryListProducts = inquiryProductRepository.findAllByInquiryIdEquals(request.getId()).stream().map(inquiryListProduct -> {
            InquiryListProductResponse inquiryListResponse = new InquiryListProductResponse();
            BeanUtils.copyProperties(inquiryListProduct, inquiryListResponse);
            return inquiryListResponse;
        }).collect(Collectors.toList());
        response.setInquiryListProductRequests(inquiryListProducts);

        response.setExternalStateName(InquiryExternalStatusEnum.getName(response.getExternalState()));
        response.setInteriorStateName(QuoteInteriorStatusEnum.getName(response.getInteriorState()));
        //获取外部流转记录
        getExternalInquiryListLog(response, inquiryList.getId(), sysUser);
        //查询内部流程
        getInqyiryLog(response, inquiryList);
        return Wrapper.success(response);
    }

    /**
     * 确认询价报价-提交审核
     * @author wrc
     * @date 2020/8/20
     */
    @Override
    public Wrapper notarizeEnquiryQuotedPriceSubmit(NotarizeEnquiryQuotedPriceSubmitRequest request, UserLoginCacheDTO sysUser) {
        Optional<Quote> byId = quoteRepository.findById(request.getId());
        if (!byId.isPresent()) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        Quote productQuotation = byId.get();
        if (OrderConstant.State.START.equals(request.getState())) {
            countList(productQuotation.getDetails(),sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_CONFIRM_INQUIRY_QUOTATION.getCode(), 1L, ConfirmInquiryQuotationOperateTypeEnum.TO_BE_VALIFY_STEP1.getCode(), 1L, ConfirmInquiryQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode());
            sendSystemMessagePur(productQuotation, MessageTemplateCode.confirm_inquiry_quotation_audit_step_1);
        }
        return auditInterior(productQuotation,  OrderConstant.State.START.equals(request.getState()) ? ConfirmQuoteOperationEnum.ACCEPT_QUOTE.getName() : request.getAuditOpinion(), request.getState(), sysUser, ConfirmQuoteOperationEnum.SUBMIT_CHECK_QUOTE.getName());
    }

    /**
     * 确认询价报价-待提交审核报价单-批量提交审核
     * @author wrc
     * @date 2020/8/20
     */
    @Override
    public Wrapper notarizeEnquiryQuotedPriceSubmitAll(NotarizeEnquiryQuotedPriceSubmitAllRequest request, UserLoginCacheDTO sysUser) {
        List<Quote> allById = quoteRepository.findAllById(request.getIds());
        if (CollectionUtils.isEmpty(allById)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        batchSendSystemMessagePur(allById, MessageTemplateCode.confirm_inquiry_quotation_audit_step_1);
        allById.forEach(productQuotation -> countList(productQuotation.getDetails(),sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_CONFIRM_INQUIRY_QUOTATION.getCode(), 1L, ConfirmInquiryQuotationOperateTypeEnum.TO_BE_VALIFY_STEP1.getCode(), 1L, ConfirmInquiryQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode()));
        return auditInteriorAll(ConfirmQuoteOperationEnum.AGREE.getName(),allById, OrderConstant.State.START, sysUser, ConfirmQuoteOperationEnum.CHECK_QUOTE.getName());
    }

    /**
     * 待提交审核报价单列表查询（一级）
     * @author wrc
     * @date 2020/8/19
     */
    @Override
    public Wrapper<PageData<ConfirmQuoteListResponse>> notarizeEnquiryQuotedPriceAuditList(ProductQuotationListRequest request, UserLoginCacheDTO sysUser) {
        Pageable page = PageRequest.of(request.getCurrent(), request.getPageSize());
        Page<Quote> result = quoteRepository.findAll(getSpecification(request, sysUser.getMemberId(), sysUser.getMemberRoleId(), OrderConstant.ConfirmQuoteQueryType.CONFIRM_QUOTE_CHECK_ONE), page);
        List<ConfirmQuoteListResponse> countryAreaListResponseList = result.getContent().stream().map(quote -> {
            ConfirmQuoteListResponse confirmQuoteListResponse = BeanUtil.copyProperties(quote, ConfirmQuoteListResponse.class);
            confirmQuoteListResponse.setInteriorState(quote.getConfirmInteriorState());
            confirmQuoteListResponse.setInteriorStateName(ConfirmQuoteInteriorStatusEnum.getName(quote.getConfirmInteriorState()));
            confirmQuoteListResponse.setExternalStateName(InquiryExternalStatusEnum.getName(confirmQuoteListResponse.getExternalState()));
            confirmQuoteListResponse.setOfferMemberId(quote.getCreateMemberId());
            confirmQuoteListResponse.setOfferMemberName(quote.getCreateMemberName());
            confirmQuoteListResponse.setOfferMemberRoleId(quote.getCreateRoleId());
            return confirmQuoteListResponse;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(result.getTotalElements(), countryAreaListResponseList));
    }

    /**
     * 确认询价报价-提交审核（一级）
     * @author wrc
     * @date 2020/8/20
     */
    @Override
    public Wrapper notarizeEnquiryQuotedPriceAudit(NotarizeEnquiryQuotedPriceSubmitRequest request, UserLoginCacheDTO sysUser) {
        Optional<Quote> byId = quoteRepository.findById(request.getId());
        if (!byId.isPresent()) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        Quote productQuotation = byId.get();
        if (OrderConstant.State.START.equals(request.getState())) {
            countList(productQuotation.getDetails(),sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_CONFIRM_INQUIRY_QUOTATION.getCode(), 1L, ConfirmInquiryQuotationOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode(), 1L, ConfirmInquiryQuotationOperateTypeEnum.TO_BE_VALIFY_STEP1.getCode());
            sendSystemMessagePur(productQuotation, MessageTemplateCode.confirm_inquiry_quotation_audit_step_2);
        } else {
            sendSystemMessagePur(productQuotation, MessageTemplateCode.confirm_inquiry_quotation_wait_audit);
            countList(productQuotation.getDetails(),sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_CONFIRM_INQUIRY_QUOTATION.getCode(), 1L, ConfirmInquiryQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode(), 1L, ConfirmInquiryQuotationOperateTypeEnum.TO_BE_VALIFY_STEP1.getCode());
        }
        return auditInterior(productQuotation,  OrderConstant.State.START.equals(request.getState()) ? ConfirmQuoteOperationEnum.ACCEPT_QUOTE.getName() : request.getAuditOpinion(), request.getState(), sysUser, ConfirmQuoteOperationEnum.CHECK_QUOTE_1.getName());
    }

    /**
     * 确认询价报价-待提交审核报价单-批量提交审核（一级）
     * @author wrc
     * @date 2020/8/20
     */
    @Override
    public Wrapper notarizeEnquiryQuotedPriceAuditAll(NotarizeEnquiryQuotedPriceSubmitAllRequest request, UserLoginCacheDTO sysUser) {
        List<Quote> allById = quoteRepository.findAllById(request.getIds());
        if (CollectionUtils.isEmpty(allById)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        batchSendSystemMessagePur(allById, MessageTemplateCode.confirm_inquiry_quotation_audit_step_2);
        allById.forEach(productQuotation ->  countList(productQuotation.getDetails(),sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_CONFIRM_INQUIRY_QUOTATION.getCode(), 1L, ConfirmInquiryQuotationOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode(), 1L, ConfirmInquiryQuotationOperateTypeEnum.TO_BE_VALIFY_STEP1.getCode()));
        return auditInteriorAll(ConfirmQuoteOperationEnum.AGREE.getName(), allById, OrderConstant.State.START, sysUser, ConfirmQuoteOperationEnum.CHECK_QUOTE_1.getName());
    }

    /**
     * 交易中心-询价报价-待审核报价单列表查询(二级)
     * @author wrc
     * @date 2020/8/20
     */
    @Override
    public Wrapper<PageData<ConfirmQuoteListResponse>> notarizeEnquiryQuotedPriceAuditListTwo(ProductQuotationListRequest request, UserLoginCacheDTO sysUser) {
        Pageable page = PageRequest.of(request.getCurrent(), request.getPageSize());
        Page<Quote> result = quoteRepository.findAll(getSpecification(request, sysUser.getMemberId(), sysUser.getMemberRoleId(), OrderConstant.ConfirmQuoteQueryType.CONFIRM_QUOTE_CHECK_TWO), page);
        List<ConfirmQuoteListResponse> countryAreaListResponseList = result.getContent().stream().map(quote -> {
            ConfirmQuoteListResponse confirmQuoteListResponse = BeanUtil.copyProperties(quote, ConfirmQuoteListResponse.class);
            confirmQuoteListResponse.setInteriorState(quote.getConfirmInteriorState());
            confirmQuoteListResponse.setInteriorStateName(ConfirmQuoteInteriorStatusEnum.getName(quote.getConfirmInteriorState()));
            confirmQuoteListResponse.setExternalStateName(InquiryExternalStatusEnum.getName(confirmQuoteListResponse.getExternalState()));
            confirmQuoteListResponse.setOfferMemberId(quote.getCreateMemberId());
            confirmQuoteListResponse.setOfferMemberName(quote.getCreateMemberName());
            confirmQuoteListResponse.setOfferMemberRoleId(quote.getCreateRoleId());

            List<InquiryProduct> inquiryProductList = quote.getInquiryProductList();
            if(!CollectionUtils.isEmpty(inquiryProductList)){
                confirmQuoteListResponse.setImgUrl(inquiryProductList.get(0).getImgUrl());
            }
            return confirmQuoteListResponse;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(result.getTotalElements(), countryAreaListResponseList));
    }

    /**
     * 确认询价报价-待提交审核报价单-提交审核（二级）
     * @author wrc
     * @date 2020/8/20
     */
    @Override
    public Wrapper notarizeEnquiryQuotedPriceAuditTwo(NotarizeEnquiryQuotedPriceSubmitRequest request, UserLoginCacheDTO sysUser) {
        Optional<Quote> byId = quoteRepository.findById(request.getId());
        if (!byId.isPresent()) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        Quote productQuotation = byId.get();
        if (OrderConstant.State.START.equals(request.getState())) {
            countList(productQuotation.getDetails(),sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_CONFIRM_INQUIRY_QUOTATION.getCode(), 1L, ConfirmInquiryQuotationOperateTypeEnum.TO_BE_CONFIRM.getCode(), 1L, ConfirmInquiryQuotationOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode());
            sendSystemMessagePur(productQuotation, MessageTemplateCode.confirm_inquiry_quotation_confirm);
        } else {
            countList(productQuotation.getDetails(),sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_CONFIRM_INQUIRY_QUOTATION.getCode(), 1L, ConfirmInquiryQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode(), 1L, ConfirmInquiryQuotationOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode());
            sendSystemMessagePur(productQuotation, MessageTemplateCode.confirm_inquiry_quotation_wait_audit);
        }
        return auditInterior(productQuotation,  OrderConstant.State.START.equals(request.getState()) ? ConfirmQuoteOperationEnum.AGREE.getName() : request.getAuditOpinion(), request.getState(), sysUser, ConfirmQuoteOperationEnum.CHECK_QUOTE_2.getName());
    }

    /**
     * 确认询价报价-待提交审核报价单-批量提交审核（二级）
     * @author wrc
     * @date 2020/8/20
     */
    @Override
    public Wrapper notarizeEnquiryQuotedPriceAuditAllTwo(NotarizeEnquiryQuotedPriceSubmitAllRequest request, UserLoginCacheDTO sysUser) {
        List<Quote> allById = quoteRepository.findAllById(request.getIds());
        if (CollectionUtils.isEmpty(allById)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        batchSendSystemMessagePur(allById, MessageTemplateCode.confirm_inquiry_quotation_confirm);
        allById.forEach(productQuotation-> countList(productQuotation.getDetails(),sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_CONFIRM_INQUIRY_QUOTATION.getCode(), 1L, ConfirmInquiryQuotationOperateTypeEnum.TO_BE_CONFIRM.getCode(),1L, ConfirmInquiryQuotationOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode()));
        return auditInteriorAll(ConfirmQuoteOperationEnum.AGREE.getName(), allById, OrderConstant.State.START, sysUser, ConfirmQuoteOperationEnum.CHECK_QUOTE_2.getName());
    }

    /**
     * 确认报价单-待确认报价单列表
     * @author wrc
     * @date 2020/8/20
     */
    @Override
    public Wrapper<PageData<ConfirmQuoteListResponse>> notarizeEnquiryQuotedPriceAffirmList(ProductQuotationListRequest request, UserLoginCacheDTO sysUser) {
        Pageable page = PageRequest.of(request.getCurrent(), request.getPageSize());
        Page<Quote> result = quoteRepository.findAll(getSpecification(request, sysUser.getMemberId(), sysUser.getMemberRoleId(), OrderConstant.ConfirmQuoteQueryType.CONFIRM_QUOTE_NOT_CONFIRM), page);
        List<ConfirmQuoteListResponse> countryAreaListResponseList = result.getContent().stream().map(quote -> {
            ConfirmQuoteListResponse confirmQuoteListResponse = BeanUtil.copyProperties(quote, ConfirmQuoteListResponse.class);
            confirmQuoteListResponse.setInteriorState(quote.getConfirmInteriorState());
            confirmQuoteListResponse.setInteriorStateName(ConfirmQuoteInteriorStatusEnum.getName(quote.getConfirmInteriorState()));
            confirmQuoteListResponse.setExternalStateName(InquiryExternalStatusEnum.getName(confirmQuoteListResponse.getExternalState()));
            confirmQuoteListResponse.setOfferMemberId(quote.getCreateMemberId());
            confirmQuoteListResponse.setOfferMemberName(quote.getCreateMemberName());
            confirmQuoteListResponse.setOfferMemberRoleId(quote.getCreateRoleId());
            return confirmQuoteListResponse;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(result.getTotalElements(), countryAreaListResponseList));
    }

    /**
     * 确认报价单-提交审核
     * @author wrc
     * @date 2020/8/20
     */
    @Override
    public Wrapper notarizeEnquiryQuotedPriceAffirm(NotarizeEnquiryQuotedPriceSubmitRequest request, UserLoginCacheDTO sysUser) {
        Quote productQuotation = quoteRepository.findById(request.getId()).orElse(null);
        if (null==productQuotation) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        Wrapper wrapper = auditInterior(productQuotation, OrderConstant.State.START.equals(request.getState()) ? ConfirmQuoteOperationEnum.ACCEPT_QUOTE.getName() : request.getAuditOpinion(), request.getState(), sysUser, ConfirmQuoteOperationEnum.CONFIRM_QUOTE.getName());
        //执行外部审核
        if (ResponseCode.SUCCESS.getCode() != wrapper.getCode()) {
            return wrapper;
        }
        Wrapper wrapperExterna = auditExternal(productQuotation, request.getAuditOpinion(), request.getState(), sysUser, ConfirmQuoteOperationEnum.CONFIRM_QUOTE.getName());
        if (OrderConstant.State.START.equals(request.getState())) {
            countList(productQuotation.getDetails(),sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_CONFIRM_INQUIRY_QUOTATION.getCode(), 0L, 0, 1L, ConfirmInquiryQuotationOperateTypeEnum.TO_BE_CONFIRM.getCode());
            sendSystemMessageSale(productQuotation, MessageTemplateCode.inquiry_quotation_result);
        } else {
            countList(productQuotation.getDetails(),sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_CONFIRM_INQUIRY_QUOTATION.getCode(), 1L, ConfirmInquiryQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode(), 1L, ConfirmInquiryQuotationOperateTypeEnum.TO_BE_CONFIRM.getCode());
            sendSystemMessagePur(productQuotation, MessageTemplateCode.confirm_inquiry_quotation_wait_audit);
        }
        return wrapperExterna;
    }

    /**
     * 确认询价报价-待确认报价单-批量提交审核
     * @author wrc
     * @date 2020/8/20
     */
    @Override
    public Wrapper notarizeEnquiryQuotedPriceAffirmAll(NotarizeEnquiryQuotedPriceSubmitAllRequest request, UserLoginCacheDTO sysUser) {
        List<Quote> allById = quoteRepository.findAllById(request.getIds());
        if (CollectionUtils.isEmpty(allById)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        Wrapper wrapper = auditInteriorAll(ConfirmQuoteOperationEnum.ACCEPT_QUOTE.getName(), allById, OrderConstant.State.START, sysUser, ConfirmQuoteOperationEnum.CONFIRM_QUOTE.getName());
        //执行外部审核
        if (ResponseCode.SUCCESS.getCode() != wrapper.getCode()) {
            return wrapper;
        }
        for (Quote productQuotation : allById) {
            auditExternal(productQuotation, null, OrderConstant.State.START, sysUser, ConfirmQuoteOperationEnum.CONFIRM_QUOTE.getName());
            countList(productQuotation.getDetails(),sysUser.getMemberId(), sysUser.getMemberRoleId(), OperateDataSourceEnum.TRADE_CONFIRM_INQUIRY_QUOTATION.getCode(), 0L, 0, 1L, ConfirmInquiryQuotationOperateTypeEnum.TO_BE_CONFIRM.getCode());
            sendSystemMessageSale(productQuotation, MessageTemplateCode.inquiry_quotation_result);
        }
        return Wrapper.success();
    }

//    /**
//     * 报价单列表查询
//     * @author wrc
//     * @date 2020/7/31
//     */
//    private String quoteQuery(ProductQuotationListRequest request, String condition) {
//        String sbList = "SELECT  rf.create_member_name as offerMemberName,rf.create_member_id as offerMemberId,rf.create_role_id as offerMemberRoleId,rf.member_id as memberId,rf.member_role_id as memberRoleId,rf.member_name as memberName,rf.inquiry_list_id as inquiryListId,rf.quotation_no as quotationNo,rf.inquiry_list_no as inquiryListNo,rf.id as id,rf.details as details,rf.delivery_time as deliveryTime,rf.quotation_as_time as quotationAsTime,rf.voucher_time as voucherTime,rf.external_state as externalState,rf.confirm_interior_state as interiorState, rf.shop_id as shopId, " +
//                " (select tip.img_url from trade_inquiry_product tip where tip.inquiry_list_id = rf.id limit 1) as imgUrl " +
//                "FROM trade_quote rf  " +
//                condition +
//                " order by  rf.voucher_time desc " +
//                " limit " +
//                request.getPageSize() +
//                " OFFSET " +
//                request.getCurrent() * request.getPageSize();
//        return sbList;
//    }
//
//    /**
//     * sql拼接
//     * @author wrc
//     * @date 2020/7/31
//     */
//    private String sqlJointList(ProductQuotationListRequest request, String condition) {
//        String sbList = "SELECT  rf.member_id as memberId,rf.member_name as memberName,rf.member_role_id as memberRoleId,rf.create_member_id as offerMemberId,rf.create_member_name as offerMemberName,rf.quotation_no as quotationNo,rf.inquiry_list_id as inquiryListId,rf.inquiry_list_no as inquiryListNo,rf.id as id,rf.details as details,rf.delivery_time as deliveryTime,rf.quotation_as_time as quotationAsTime,rf.voucher_time as voucherTime,rf.external_state as externalState,rf.confirm_interior_state as interiorState, " +
//                " (select tip.img_url from trade_inquiry_product tip where tip.inquiry_list_id = rf.id limit 1) as imgUrl " +
//                "FROM trade_quote rf  " +
//                condition +
//                " order by  rf.id desc " +
//                " limit " +
//                request.getPageSize() +
//                " OFFSET " +
//                request.getCurrent() * request.getPageSize();
//        return sbList;
//    }
//
//    /**
//     * sql拼接
//     * queryType 查询类型：1.报价单查询 2. 待新增报价单查询 3.待审核报价单（一级） 4.待审核报价单（二级） 5.待提交报价单
//     * @author wrc
//     * @date 2020/7/31
//     */
//    private String sqlJointCondition(ProductQuotationListRequest request, Long memberId, Long memberRoleId, Integer queryType) {
//        StringBuilder sbCondition = new StringBuilder();
//        sbCondition.append(" where  rf.member_id =");
//        sbCondition.append(memberId);
//        sbCondition.append(" and  rf.member_role_id =");
//        sbCondition.append(memberRoleId);
//
//        if (null != request && null != request.getShopId() && request.getShopId() > 0) {
//            sbCondition.append(" AND  rf.shop_id =");
//            sbCondition.append(request.getShopId());
//        }
//
//        if (null != request && null != request.getDetails() && !request.getDetails().isEmpty()) {
//            sbCondition.append(" AND  rf.details like  '%");
//            sbCondition.append(request.getDetails());
//            sbCondition.append("%'");
//        }
//        if (null != request && null != request.getInquiryListNo() && !request.getInquiryListNo().isEmpty()) {
//            sbCondition.append(" AND  rf.inquiry_list_no like  '%");
//            sbCondition.append(request.getInquiryListNo());
//            sbCondition.append("%'");
//        }
//
//        if (null != request && null != request.getKeyword() && !request.getKeyword().isEmpty()) {
//            sbCondition.append(" AND (rf.inquiry_list_no like  '%");
//            sbCondition.append(request.getKeyword());
//            sbCondition.append("%'");
//            sbCondition.append(" or  rf.quotation_no like  '%");
//            sbCondition.append(request.getKeyword());
//            sbCondition.append("%')") ;
//        }
//
//        if (null != request && null != request.getQuotationNo() && !request.getQuotationNo().isEmpty()) {
//            sbCondition.append(" AND  rf.quotation_no like  '%");
//            sbCondition.append(request.getQuotationNo());
//            sbCondition.append("%'");
//        }
//        if (null != request && null != request.getMemberName() && !request.getMemberName().isEmpty()) {
//            sbCondition.append(" AND  rf.member_name like  '%");
//            sbCondition.append(request.getMemberName());
//            sbCondition.append("%'");
//        }
//        if (null != request && null != request.getOfferMemberName() && !request.getOfferMemberName().isEmpty()) {
//            sbCondition.append(" AND  rf.create_member_name like  '%");
//            sbCondition.append(request.getOfferMemberName());
//            sbCondition.append("%'");
//        }
//
//        if (null != request && null != request.getStartDocumentsTime() && null != request.getEndDocumentsTime()) {
//            sbCondition.append(" AND  rf.voucher_time BETWEEN ");
//            sbCondition.append(request.getStartDocumentsTime());
//            sbCondition.append(" and ");
//            sbCondition.append(request.getEndDocumentsTime());
//        }
//        if (null != request && null != request.getStartDocumentsTime() && null != request.getEndDocumentsTime()) {
//            sbCondition.append(" AND  rf.voucher_time BETWEEN ");
//            sbCondition.append(request.getStartDocumentsTime());
//            sbCondition.append(" and ");
//            sbCondition.append(request.getEndDocumentsTime());
//        }
//        //报价单查询
//        if (queryType.equals(OrderConstant.ConfirmQuoteQueryType.CONFIRM_QUOTE_ALL)) {
//            sbCondition.append(" AND  rf.interior_state = 5 ");
//            if (null != request && null != request.getExternalState()) {
//                sbCondition.append(" AND  rf.external_state =  ");
//                sbCondition.append(request.getExternalState());
//            }
//            if (null != request && null != request.getInteriorState()) {
//                sbCondition.append(" AND  rf.confirm_interior_state =  ");
//                sbCondition.append(request.getInteriorState());
//            }
//        } else if (queryType.equals(OrderConstant.ConfirmQuoteQueryType.CONFIRM_QUOTE_NOT_SUBMIT)) {
//            sbCondition.append(" and rf.confirm_interior_state = 1 ");                                      //待提交审核报价单
//        } else if (queryType.equals(OrderConstant.ConfirmQuoteQueryType.CONFIRM_QUOTE_CHECK_ONE)) {
//            sbCondition.append(" and  rf.confirm_interior_state = 2 ");                                     //待审核报价单(一级)
//        } else if (queryType.equals(OrderConstant.ConfirmQuoteQueryType.CONFIRM_QUOTE_CHECK_TWO)) {
//            sbCondition.append(" and rf.confirm_interior_state = 3 ");                                      //待审核报价单(二级)
//        } else if (queryType.equals(OrderConstant.ConfirmQuoteQueryType.CONFIRM_QUOTE_NOT_CONFIRM)) {
//            sbCondition.append(" and rf.confirm_interior_state in (4,6,7,8) and rf.external_state = 3 ");   //待确认报价单
//        }
////        else if (queryType.equals(OrderConstant.ConfirmQuoteQueryType.PRODUCT_QUOTATION_TO_BE_SUBMITTED)) {
////            sbCondition.append(" and rf.confirm_interior_state = 4");
////        }
//        return sbCondition.toString();
//    }
//
//    /**
//     * sql拼接
//     * @author wrc
//     * @date 2020/7/31
//     */
//    private String quoteSqlJointCount(String condition) {
//        String sbCount = "SELECT count(DISTINCT rf.id) FROM trade_quote rf " +
//                condition;
//        return sbCount;
//    }

    /**
     * 工作流内部审核
     * @param: cause 审核原因, state 审核状态1.通过 0.不通过 -1, inquiryList：商品询价单
     * @return 执行工作流结果
     * @author wrc
     * 2020/8/11 17:23
     */
    private Wrapper auditInterior(Quote productQuotation, String cause, Integer state, UserLoginCacheDTO sysUser, String operation) {
        //添加需求报价单内部流转记录
        TaskExecuteVO processStartVO = new TaskExecuteVO();
        processStartVO.setRoleId(sysUser.getMemberRoleId());
        processStartVO.setAgree(state);
        processStartVO.setTaskId(productQuotation.getConfirmInteriorTaskId());
        processStartVO.setMemberId(sysUser.getMemberId());
        processStartVO.setProcessKey(ProcessEnum.TRADE_CONFIRM_QUOTE_INNER.getProcessKey());
        processStartVO.setDataId(productQuotation.getId());
        Wrapper<SimpleTaskCompleteVO> taskResultVOWrapper = processFeign.completeSimpleTask(processStartVO);
        if (ResponseCode.SUCCESS.getCode() == taskResultVOWrapper.getCode()) {
            productQuotation.setConfirmInteriorTaskId(taskResultVOWrapper.getData().getTaskId());
            productQuotation.setConfirmInteriorState(taskResultVOWrapper.getData().getStatus());
            productQuotation.setUpdateTime(System.currentTimeMillis());
            quoteRepository.save(productQuotation);
            ConfirmQuoteInteriorRecord notarizeEnquiryQuotedPriceLog = new ConfirmQuoteInteriorRecord();
            notarizeEnquiryQuotedPriceLog.setCreateRoleId(sysUser.getUserId());
            notarizeEnquiryQuotedPriceLog.setRoleId(sysUser.getMemberRoleId());
            notarizeEnquiryQuotedPriceLog.setCreateTime(System.currentTimeMillis());
            notarizeEnquiryQuotedPriceLog.setDepartment(sysUser.getUserOrgName());
            notarizeEnquiryQuotedPriceLog.setState(taskResultVOWrapper.getData().getStatus());
            notarizeEnquiryQuotedPriceLog.setRoleName(sysUser.getUserName());
            notarizeEnquiryQuotedPriceLog.setPosition(sysUser.getUserJobTitle());
            notarizeEnquiryQuotedPriceLog.setOperationTime(System.currentTimeMillis());
            notarizeEnquiryQuotedPriceLog.setOperation(operation);
            notarizeEnquiryQuotedPriceLog.setRoleName(sysUser.getUserName());
            notarizeEnquiryQuotedPriceLog.setNotarizeEnquiryQuotedPriceId(productQuotation.getId());
            notarizeEnquiryQuotedPriceLog.setAuditOpinion(cause);
            confirmQuoteInteriorRecordRepository.save(notarizeEnquiryQuotedPriceLog);
        }
        return taskResultVOWrapper;
    }


    /**
     * 工作流外部部审核
     * @param: cause 审核原因, state 审核状态1.通过 0.不通过 -1, inquiryList：商品询价单
     * @return 执行工作流结果
     * @author wrc
     * 2020/8/11 17:23
     */
    private Wrapper auditExternal(Quote productQuotation, String cause, Integer state, UserLoginCacheDTO sysUser, String operation) {
        //添加需求报价单内部流转记录
        TaskExecuteVO processStartVO = new TaskExecuteVO();
        processStartVO.setRoleId(sysUser.getMemberRoleId());
        processStartVO.setAgree(state);
        processStartVO.setTaskId(productQuotation.getExternalTaskId());
        processStartVO.setMemberId(sysUser.getMemberId());
        processStartVO.setProcessKey(ProcessEnum.TRADE_INQUIRY_EXTERNAL.getProcessKey());
        processStartVO.setDataId(productQuotation.getInquiryListId());
        Wrapper<SimpleTaskCompleteVO> taskResultVOWrapper = processFeign.completeSimpleTask(processStartVO);
        if (ResponseCode.SUCCESS.getCode() != taskResultVOWrapper.getCode()) {
            return taskResultVOWrapper;
        }
        productQuotation.setExternalTaskId(taskResultVOWrapper.getData().getTaskId());
        productQuotation.setExternalState(taskResultVOWrapper.getData().getStatus());
        productQuotation.setUpdateTime(System.currentTimeMillis());
        quoteRepository.save(productQuotation);
        Optional<Inquiry> byIdInquiryList = inquiryRepository.findById(productQuotation.getInquiryListId());
        if (!byIdInquiryList.isPresent()) {
            return Wrapper.fail(ResponseCode.PURCHASE_DATA_RECORDS_DON_T_EXIST);
        }
        Inquiry inquiryList = byIdInquiryList.get();
        inquiryList.setExternalTaskId(taskResultVOWrapper.getData().getTaskId());
        inquiryList.setExternalState(taskResultVOWrapper.getData().getStatus());
        inquiryList.setUpdateTime(System.currentTimeMillis());
        inquiryRepository.save(inquiryList);
        InquiryExternalRecord externalInquiryListLogInquiryListLog = new InquiryExternalRecord();
        externalInquiryListLogInquiryListLog.setCreateRoleId(sysUser.getUserId());
        externalInquiryListLogInquiryListLog.setRoleId(sysUser.getMemberRoleId());
        externalInquiryListLogInquiryListLog.setCreateTime(System.currentTimeMillis());
        externalInquiryListLogInquiryListLog.setState(taskResultVOWrapper.getData().getStatus());
        externalInquiryListLogInquiryListLog.setRoleName(sysUser.getMemberRoleName());
        externalInquiryListLogInquiryListLog.setOperationTime(System.currentTimeMillis());
        externalInquiryListLogInquiryListLog.setOperation(operation);
        externalInquiryListLogInquiryListLog.setRoleName(sysUser.getMemberRoleName());
        externalInquiryListLogInquiryListLog.setInquiryListId(productQuotation.getInquiryListId());
        externalInquiryListLogInquiryListLog.setAuditOpinion(cause);
        inquiryExternalRecordRepository.save(externalInquiryListLogInquiryListLog);
        return Wrapper.success();
    }


    /**
     * 工作流内部批量审核
     * @param: cause 审核原因, state 审核状态1.通过 0.不通过 -1, inquiryList：商品询价单
     * @return 执行工作流结果
     * @author wrc 2020/8/11 17:23
     */
    private Wrapper auditInteriorAll(String auditOpinion, List<Quote> productQuotations, Integer state, UserLoginCacheDTO sysUser, String operation) {
        //添加需求报价单内部流转记录
        for (Quote productQuotation : productQuotations) {
            TaskExecuteVO processStartVO = new TaskExecuteVO();
            processStartVO.setRoleId(sysUser.getMemberRoleId());
            processStartVO.setAgree(state);
            processStartVO.setTaskId(productQuotation.getConfirmInteriorTaskId());
            processStartVO.setMemberId(sysUser.getMemberId());
            processStartVO.setProcessKey(ProcessEnum.TRADE_CONFIRM_QUOTE_INNER.getProcessKey());
            processStartVO.setDataId(productQuotation.getId());
            Wrapper<SimpleTaskCompleteVO> taskResultVOWrapper = processFeign.completeSimpleTask(processStartVO);
            if (ResponseCode.SUCCESS.getCode() != taskResultVOWrapper.getCode()) {
                return taskResultVOWrapper;
            }
            productQuotation.setConfirmInteriorTaskId(taskResultVOWrapper.getData().getTaskId());
            productQuotation.setConfirmInteriorState(taskResultVOWrapper.getData().getStatus());
            productQuotation.setUpdateTime(System.currentTimeMillis());
            quoteRepository.save(productQuotation);
            ConfirmQuoteInteriorRecord notarizeEnquiryQuotedPriceLog = new ConfirmQuoteInteriorRecord();
            notarizeEnquiryQuotedPriceLog.setCreateRoleId(sysUser.getUserId());
            notarizeEnquiryQuotedPriceLog.setRoleId(sysUser.getMemberRoleId());
            notarizeEnquiryQuotedPriceLog.setCreateTime(System.currentTimeMillis());
            notarizeEnquiryQuotedPriceLog.setDepartment(sysUser.getUserOrgName());
            notarizeEnquiryQuotedPriceLog.setState(taskResultVOWrapper.getData().getStatus());
            notarizeEnquiryQuotedPriceLog.setRoleName(sysUser.getUserName());
            notarizeEnquiryQuotedPriceLog.setPosition(sysUser.getUserJobTitle());
            notarizeEnquiryQuotedPriceLog.setOperationTime(System.currentTimeMillis());
            notarizeEnquiryQuotedPriceLog.setOperation(operation);
            notarizeEnquiryQuotedPriceLog.setRoleName(sysUser.getUserName());
            notarizeEnquiryQuotedPriceLog.setNotarizeEnquiryQuotedPriceId(productQuotation.getId());
            notarizeEnquiryQuotedPriceLog.setAuditOpinion(auditOpinion);
            confirmQuoteInteriorRecordRepository.save(notarizeEnquiryQuotedPriceLog);
        }
        return Wrapper.success();
    }


    /**
     * 增加减记录操作数据记录
     * @author wrc
     * @date 2020/11/26
     */
    public void countList(String increaseTitle,Long memberId, Long memberRoleId, Integer dataSource, Long IncreaseCount, Integer increaseOperateType, Long reduceCount, Integer reduceOperateType) {
        try {
            OperateNoticeVO operateNoticeVO = new OperateNoticeVO();
            operateNoticeVO.setIncreaseTitle(increaseTitle);
            operateNoticeVO.setDataSource(dataSource);
            operateNoticeVO.setMemberId(memberId);
            operateNoticeVO.setRoleId(memberRoleId);
            operateNoticeVO.setReduceCount(reduceCount);
            operateNoticeVO.setReduceOperateType(reduceOperateType);
            operateNoticeVO.setIncreaseCount(IncreaseCount);
            operateNoticeVO.setIncreaseOperateType(increaseOperateType);
            reportControllerFeign.addOperateNotice(operateNoticeVO);
        } catch (Exception e) {
            log.error("增加减记录操作数据记录异常", e);
        }
    }

    /**
     * 采购商发消息
     */
    @Async
    public void sendSystemMessagePur(Quote productQuotation, String name) {
        try {
            SystemMessageRequest systemMessageRequest = new SystemMessageRequest();
            systemMessageRequest.setMemberId(productQuotation.getMemberId());
            systemMessageRequest.setRoleId(productQuotation.getMemberRoleId());
            systemMessageRequest.setMessageNotice(name);
            systemMessageRequest.setParams(Arrays.asList(productQuotation.getQuotationNo(), productQuotation.getDetails()));
            systemMessageControllerFeign.sendSystemMessage(systemMessageRequest);
        } catch (Exception e) {
            log.error("发送订单通知消息异常", e);
        }
    }

    /**
     * 销售商发消息
     */
    @Async
    public void sendSystemMessageSale(Quote productQuotation, String name) {
        try {
            SystemMessageRequest systemMessageRequest = new SystemMessageRequest();
            systemMessageRequest.setMemberId(productQuotation.getCreateMemberId());
            systemMessageRequest.setRoleId(productQuotation.getCreateRoleId());
            systemMessageRequest.setMessageNotice(name);
            systemMessageRequest.setParams(Arrays.asList(productQuotation.getQuotationNo(), productQuotation.getDetails()));
            systemMessageControllerFeign.sendSystemMessage(systemMessageRequest);
        } catch (Exception e) {
            log.error("发送订单通知消息异常", e);
        }
    }

    /**
     * 发消息
     */
    @Async
    public void batchSendSystemMessagePur(List<Quote> inquiryLists, String name) {
        try {
            List<SystemMessageRequest> collect = inquiryLists.stream().map(temp -> {
                SystemMessageRequest systemMessageRequest = new SystemMessageRequest();
                systemMessageRequest.setMemberId(temp.getMemberId());
                systemMessageRequest.setRoleId(temp.getMemberRoleId());
                systemMessageRequest.setMessageNotice(name);
                systemMessageRequest.setParams(Arrays.asList(temp.getQuotationNo(), temp.getDetails()));
                return systemMessageRequest;
            }).collect(Collectors.toList());
            systemMessageControllerFeign.batchSendSystemMessage(collect);
        } catch (Exception e) {
            log.error("发送订单通知消息异常", e);
        }
    }


    /**
     * 获取询价单内部操作流程
     */
    private void getInqyiryLog(NotarizeEnquiryQuotedPriceDetailsResponse response, Inquiry inquiryList) {
        List<InquiryInteriorRecord> interiorLogs = inquiryInteriorRecordRepository.findAllByInquiryListIdEquals(inquiryList.getId());
        //查询内部流转
        InternalProcessQueryVO taskParamQueryVO = new InternalProcessQueryVO();
        taskParamQueryVO.setProcessKey(ProcessEnum.TRADE_INQUIRY_INNER.getProcessKey());
        Wrapper<SimpleProcessDefVO> listWrapper = processFeign.findSimpleInternalTaskDefinitions(taskParamQueryVO);
        List<LogStateResponse> interiorList = new ArrayList<>();
        if (ResponseCode.SUCCESS.getCode() != listWrapper.getCode()) {
            return;
        }
        List<SimpleTaskVO> data = listWrapper.getData().getTasks();
        data.forEach(taskStepQueryVO -> {
            LogStateResponse workflowLog = new LogStateResponse();
            workflowLog.setState(taskStepQueryVO.getTaskStep());
            workflowLog.setOperationalProcess(taskStepQueryVO.getTaskName());
            workflowLog.setRoleName(taskStepQueryVO.getRoleName());
            if (!CollectionUtils.isEmpty(interiorLogs)) {
                int step = interiorLogs.get(interiorLogs.size() - 1).getState()-1;
                workflowLog.setIsExecute(step >= taskStepQueryVO.getTaskStep() ? OrderConstant.State.START : OrderConstant.State.STOP);
            } else {
                workflowLog.setIsExecute(OrderConstant.State.STOP);
            }
            interiorList.add(workflowLog);
        });
        if(!CollectionUtils.isEmpty(interiorList)){
            interiorList.get(0).setIsExecute(OrderConstant.State.START );
        }
        response.setInteriorRequisitionFormStateResponses(interiorList);
        if (CollectionUtils.isEmpty(interiorLogs)) {
            return;
        }
        List<InteriorInquiryListLogResponse> interiorLogsResponse = interiorLogs.stream().map(interiorInquiryListLog -> {
            InteriorInquiryListLogResponse interiorInquiryListLogResponse = new InteriorInquiryListLogResponse();
            BeanUtils.copyProperties(interiorInquiryListLog, interiorInquiryListLogResponse);
            interiorInquiryListLogResponse.setStateName(InquiryInteriorStatusEnum.getName(interiorInquiryListLogResponse.getState()));
            return interiorInquiryListLogResponse;
        }).collect(Collectors.toList());
        response.setInteriorInquiryListLogResponses(interiorLogsResponse.stream().sorted(Comparator.comparing(InteriorInquiryListLogResponse::getOperationTime)).collect(Collectors.toList()));
    }

    /**
     * 配置外部流程记录和状态
     */
    private void getExternalLog(ProductQuotationDetailsResponse productQuotationDetailsResponse, Long id, UserLoginCacheDTO sysUser) {
        //获取外部流转记录
        List<InquiryExternalRecord> logs = inquiryExternalRecordRepository.findAllByInquiryListIdEquals(id);
        //外部单据流转记录
        List<LogStateResponse> externalQuotationStateResponses = new ArrayList<>();
        ExternalProcessQueryVO taskStepVO = new ExternalProcessQueryVO();
        taskStepVO.setProcessKey(ProcessEnum.TRADE_INQUIRY_EXTERNAL.getProcessKey());
        taskStepVO.setRoleId(sysUser.getMemberRoleId());
        Wrapper<SimpleProcessDefVO> listWrapper = processFeign.findSimpleExternalTaskDefinitions(taskStepVO);
        if (ResponseCode.SUCCESS.getCode() != listWrapper.getCode()) {
            throw new RuntimeException(listWrapper.getMessage());
        }
        List<SimpleTaskVO> data = listWrapper.getData().getTasks();
        data.forEach(taskStepQueryVO -> {
            LogStateResponse externalRequisitionFormResponse = new LogStateResponse();
            externalRequisitionFormResponse.setState(taskStepQueryVO.getTaskStep());
            externalRequisitionFormResponse.setOperationalProcess(taskStepQueryVO.getTaskName());
            externalRequisitionFormResponse.setRoleName(taskStepQueryVO.getRoleName());
            if (CollectionUtils.isEmpty(logs)) {
                externalRequisitionFormResponse.setIsExecute(OrderConstant.State.STOP);
            } else {
                //最后一个执行步骤
                Integer state = logs.get(logs.size() - 1).getState();
                externalRequisitionFormResponse.setIsExecute(state >= taskStepQueryVO.getTaskStep() ? OrderConstant.State.START : OrderConstant.State.STOP);
            }
            externalQuotationStateResponses.add(externalRequisitionFormResponse);
        });
        productQuotationDetailsResponse.setExternalQuotationStateResponses(externalQuotationStateResponses);
        if (CollectionUtils.isEmpty(logs)) {
            return;
        }
        List<ExternalInquiryListLogResponse> externalInquiryListLogResponses = logs.stream().map(temp -> {
            ExternalInquiryListLogResponse response = new ExternalInquiryListLogResponse();
            BeanUtils.copyProperties(temp, response);
            response.setStateName(InquiryExternalStatusEnum.getName(response.getState()));
            return response;
        }).collect(Collectors.toList());
        productQuotationDetailsResponse.setExternalRequisitionFormResponses(externalInquiryListLogResponses);
    }


    /**
     * 配置内部流程记录和状态
     */
    private void getinteriorLog(ProductQuotationDetailsResponse productQuotationDetailsResponse, Long id, UserLoginCacheDTO sysUser) {
        //获取外部流转记录
        List<ConfirmQuoteInteriorRecord> logs = confirmQuoteInteriorRecordRepository.findAllByNotarizeEnquiryQuotedPriceId(id);
        //内部单据流转记录
        InternalProcessQueryVO taskStepVO = new InternalProcessQueryVO();
        taskStepVO.setMemberId(sysUser.getMemberId());
        taskStepVO.setProcessKey(ProcessEnum.TRADE_CONFIRM_QUOTE_INNER.getProcessKey());
        Wrapper<SimpleProcessDefVO> listWrapper = processFeign.findSimpleInternalTaskDefinitions(taskStepVO);
        if (ResponseCode.SUCCESS.getCode() != listWrapper.getCode()) {
            throw new RuntimeException(listWrapper.getMessage());
        }
        List<SimpleTaskVO> data = listWrapper.getData().getTasks();
        List<LogStateResponse> collect = data.stream().map(temp -> {
            LogStateResponse externalRequisitionFormResponse = new LogStateResponse();
            externalRequisitionFormResponse.setState(temp.getTaskStep());
            externalRequisitionFormResponse.setOperationalProcess(temp.getTaskName());
            externalRequisitionFormResponse.setRoleName(temp.getRoleName());
            if(CollectionUtils.isEmpty(logs)){
                externalRequisitionFormResponse.setIsExecute(OrderConstant.State.STOP);
            }else{
                //最后一个执行了的状态
                Integer state = logs.get(logs.size() - 1).getState()-1;
                externalRequisitionFormResponse.setIsExecute(state >= temp.getTaskStep() ? OrderConstant.State.START : OrderConstant.State.STOP);
            }
            return externalRequisitionFormResponse;
        }).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(collect)){
            collect.get(0).setIsExecute(OrderConstant.State.START);
        }
        productQuotationDetailsResponse.setInteriorQuotationStateResponses(collect);
        if (CollectionUtils.isEmpty(logs)) {
            return;
        }
        List<InteriorProductQuotationLogResponse> logResponses = logs.stream().map(temp -> {
            InteriorProductQuotationLogResponse response = new InteriorProductQuotationLogResponse();
            BeanUtils.copyProperties(temp, response);
            response.setStateName(ConfirmQuoteInteriorStatusEnum.getName(response.getState()));
            return response;
        }).collect(Collectors.toList());
        productQuotationDetailsResponse.setInteriorQuotationLogResponses(logResponses);
    }

    /**
     * 询价单外部操作流程记录和状态数据配置
     */
    private void getExternalInquiryListLog(NotarizeEnquiryQuotedPriceDetailsResponse response, Long id, UserLoginCacheDTO sysUser) {
        List<InquiryExternalRecord> allByInquiryListIdEquals = inquiryExternalRecordRepository.findAllByInquiryListIdEquals(id);
        //外部单据流转记录
        List<LogStateResponse> externalQuotationStateResponses = new ArrayList<>();
        ExternalProcessQueryVO taskStepVO = new ExternalProcessQueryVO();
        taskStepVO.setProcessKey(ProcessEnum.TRADE_INQUIRY_EXTERNAL.getProcessKey());
        taskStepVO.setRoleId(sysUser.getMemberRoleId());
        Wrapper<SimpleProcessDefVO> listWrapper = processFeign.findSimpleExternalTaskDefinitions(taskStepVO);
        if (ResponseCode.SUCCESS.getCode() != listWrapper.getCode()) {
            throw new RuntimeException(listWrapper.getMessage());
        }
        List<SimpleTaskVO> data = listWrapper.getData().getTasks();
        data.forEach(taskStepQueryVO -> {
            LogStateResponse externalRequisitionFormResponse = new LogStateResponse();
            externalRequisitionFormResponse.setState(taskStepQueryVO.getTaskStep());
            externalRequisitionFormResponse.setRoleName(taskStepQueryVO.getRoleName());
            externalRequisitionFormResponse.setOperationalProcess(taskStepQueryVO.getTaskName());
            if (CollectionUtils.isEmpty(allByInquiryListIdEquals)) {
                externalRequisitionFormResponse.setIsExecute(OrderConstant.State.START);
            } else {
                Integer state = allByInquiryListIdEquals.get(allByInquiryListIdEquals.size() - 1).getState();
                externalRequisitionFormResponse.setIsExecute(state >= taskStepQueryVO.getTaskStep() ? OrderConstant.State.START : OrderConstant.State.STOP);
            }
            externalQuotationStateResponses.add(externalRequisitionFormResponse);
        });
        if(!CollectionUtils.isEmpty(externalQuotationStateResponses)){
            externalQuotationStateResponses.get(0).setIsExecute(OrderConstant.State.START );
        }
        response.setExternalInquiryListStateResponses(externalQuotationStateResponses);
        if (CollectionUtils.isEmpty(allByInquiryListIdEquals)) {
            return;
        }
        List<ExternalInquiryListLogResponse> externalInquiryListLogResponses = allByInquiryListIdEquals.stream().map(temp -> {
            ExternalInquiryListLogResponse responseLog = new ExternalInquiryListLogResponse();
            BeanUtils.copyProperties(temp, responseLog);
            responseLog.setStateName(InquiryExternalStatusEnum.getName(responseLog.getState()));
            return responseLog;
        }).collect(Collectors.toList());
        response.setExternalInquiryListLogResponses(externalInquiryListLogResponses);
    }


}
